package com.jsbb.service.sys;

import com.jsbb.mapper.sys.SysRegionMapper;
import com.jsbb.entity.sys.SysRegion;
import com.jsbb.vo.sys.SysRegionListVo;
import com.jsbb.vo.sys.SysRegionTreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysRegionService {

    @Autowired
    private SysRegionMapper sysRegionMapper;

    public List<SysRegionTreeVo> tree() {
        List<SysRegionTreeVo> result = new ArrayList<>();
        List<SysRegion> list = sysRegionMapper.selectByCondition(null);
        for (SysRegion r : list) {
            SysRegionTreeVo sysRegionTreeVo = new SysRegionTreeVo();
            if (r.getPid() == 0) {
                sysRegionTreeVo.setId(Long.valueOf(r.getId()));
                sysRegionTreeVo.setName(r.getName());
                sysRegionTreeVo.setChildren(getChildren(list, r.getId()));
                result.add(sysRegionTreeVo);
            }
        }
        return result;
    }

    private List<SysRegionTreeVo> getChildren(List<SysRegion> list, Long id) {
        List<SysRegionTreeVo> lists = new ArrayList();
        for (SysRegion region : list) {
            SysRegionTreeVo sysRegionTreeVo = new SysRegionTreeVo();
            if (region.getPid().equals(id)) {
                sysRegionTreeVo.setId(Long.valueOf(region.getId()));
                sysRegionTreeVo.setName(region.getName());
                sysRegionTreeVo.setChildren(getChildren(list, region.getId()));
                lists.add(sysRegionTreeVo);
            }
        }
        return lists;
    }

    public List<SysRegionListVo> list(Long pid) {
        List<SysRegion> list = sysRegionMapper.selectByCondition(pid);
        List<SysRegionListVo> result = new ArrayList<>();
        for (SysRegion sysRegion : list) {
            SysRegionListVo sysRegionVo = new SysRegionListVo();
            BeanUtils.copyProperties(sysRegion, sysRegionVo);
            result.add(sysRegionVo);
        }
        return result;
    }

    public SysRegion get(Long id) {
        return sysRegionMapper.selectByPrimaryKey(id);
    }
}
